package com.wing.sell.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.wing.common.enums.PurEnum;
import com.wing.common.utils.UniqueIdGeneratorUtil;


import com.wing.sell.dao.SelBarterGoodsRecordsDao;
import com.wing.sell.model.entity.*;
import com.wing.sell.model.request.SelBarterGoodRecordsUpdateForm;
import com.wing.sell.model.request.SelGoodsLogisticsDetailAddForm;
import com.wing.sell.model.response.SelBarterGoodRecordsSearchVo;
import com.wing.sell.model.response.SelBarterGoodsRecordDetailVo;
import com.wing.sell.service.SelBarterGoodsRecordsDetailService;
import com.wing.sell.service.SelBarterGoodsRecordsService;
import com.wing.sell.service.SelGoodsLogisticsDetailService;
import com.wing.sell.service.SelGoodsLogisticsService;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;


/**
 * 退货记录-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class SelBarterGoodsRecordsServiceImpl extends ServiceImpl<SelBarterGoodsRecordsDao, SelBarterGoodsRecords> implements SelBarterGoodsRecordsService {

    @Autowired
    private SelBarterGoodsRecordsDetailService selBarterGoodsRecordsDetailService;

    @Autowired
    private SelGoodsLogisticsService selGoodsLogisticsService;

    @Autowired
    private SelGoodsLogisticsDetailService selGoodsLogisticsDetailService;

    /**
     * 查询换货详情
     *
     * @param pg
     * @param params
     * @return
     */
    @Override
    public Page<SelBarterGoodRecordsSearchVo> pageList4app(Page<SelBarterGoodRecordsSearchVo> pg, Map<String, Object> params) {
        List<SelBarterGoodRecordsSearchVo> list = baseMapper.list4app(pg, params);
        pg.setRecords(list);
        return pg;
    }

    /**
     * 添加换货记录
     *
     * @param selBarterGoodRecordsUpdateForm
     * @return
     */
    @Override
    public int addBarterRecordsGoods(SelBarterGoodRecordsUpdateForm selBarterGoodRecordsUpdateForm) {
        //1. 添加记录
        SelBarterGoodsRecords records = new SelBarterGoodsRecords();
        BeanUtil.copyProperties(selBarterGoodRecordsUpdateForm, records, true);
        records.setStatus(PurEnum.barterGoodStatus.DSH.getCode());
        String code = UniqueIdGeneratorUtil.generateUniqueId("HH", "yyyyMMdd", 1000, 9999);
        records.setCode(code);
        records.setCreateTime(LocalDateTime.now());
        records.setCreatorName(JwtUtils.getLoginUsername());
        records.setCreator(JwtUtils.getLoginUserId());
        boolean save = this.save(records);
        if (save) {
            //2. 添加明细
            List<SelBarterGoodsRecordsDetail> purBarterRecordDetails = selBarterGoodRecordsUpdateForm.getSelBarterGoodsRecordsDetail();
            if (CollectionUtils.isNotEmpty(purBarterRecordDetails)) {
                purBarterRecordDetails.forEach(info -> {
                    info.setRecordId(records.getId());
                    info.setCreateTime(LocalDateTime.now());
                    info.setCreatorName(JwtUtils.getLoginUsername());
                    info.setCreator(JwtUtils.getLoginUserId());
                });
                boolean saveBatch = selBarterGoodsRecordsDetailService.saveBatch(purBarterRecordDetails);
                if (saveBatch) {
                    return 1;
                }
            } else {
                return 1;
            }
        }
        return 0;
    }

    /**
     * 修改换货记录
     *
     * @param form
     * @return
     */
    @Override
    public int updateBarterRecordsGoods(SelBarterGoodRecordsUpdateForm form) {
        //1.修改记录
        SelBarterGoodsRecords byId = this.getById(form.getId());
        BeanUtil.copyProperties(form, byId, true);
        byId.setStatus(PurEnum.barterGoodStatus.DSH.getCode());
        byId.setUpdateTime(LocalDateTime.now());
        byId.setModifier(JwtUtils.getLoginUserId());
        byId.setModifierName(JwtUtils.getLoginUsername());
        boolean update = this.updateById(byId);
        //修改
        if (update) {
            //1.删除 添加
            QueryWrapper<SelBarterGoodsRecordsDetail> qw = new QueryWrapper<>();
            qw.eq("record_id", byId.getId());
            qw.eq("is_deleted", false);
            boolean remove = this.selBarterGoodsRecordsDetailService.remove(qw);
            if (remove) {
                List<SelBarterGoodsRecordsDetail> selbarters = form.getSelBarterGoodsRecordsDetail();
                if (CollectionUtils.isNotEmpty(selbarters)) {
                    selbarters.forEach(info -> {
                        info.setRecordId(byId.getId());
                        info.setCreateTime(LocalDateTime.now());
                        info.setModifier(JwtUtils.getLoginUserId());
                        info.setModifierName(JwtUtils.getLoginUsername());
                        info.setCreator(JwtUtils.getLoginUserId());
                        info.setCreatorName(JwtUtils.getLoginUsername());
                        info.setCreateTime(LocalDateTime.now());
                    });
                }
                boolean b = this.selBarterGoodsRecordsDetailService.saveBatch(selbarters);
                if (b) {
                    return 1;
                }
            }
        }
        return 0;
    }

    /**
     * 查询详情
     *
     * @param recordId
     * @return
     */
    @Override
    public SelBarterGoodsRecordDetailVo getByDetailId(String recordId) {
        //查询详情
        SelBarterGoodsRecordDetailVo byId = this.baseMapper.getByDetailinfoBy(recordId);
        //查询物流详情
        QueryWrapper<SelBarterGoodsRecordsDetail> qw = new QueryWrapper<>();
        qw.eq("record_id", byId.getId());
        qw.eq("is_deleted", false);
        List<SelBarterGoodsRecordsDetail> selBarterGoodsRecordsDetails = this.selBarterGoodsRecordsDetailService.list(qw);
        byId.setSelBarterRecordDetails(selBarterGoodsRecordsDetails);
        //查询收货信息
        QueryWrapper<SelGoodsLogistics> detailQueryWrapper = new QueryWrapper<>();
        detailQueryWrapper.eq("record_id", byId.getId());
        detailQueryWrapper.eq("module_type", PurEnum.moduleTypeBylogistics.XSHH.getCode());
        detailQueryWrapper.eq("good_type", PurEnum.goodSellType.TH.getCode());
        detailQueryWrapper.eq("is_deleted", false);
        List<SelGoodsLogistics> list = this.selGoodsLogisticsService.list(detailQueryWrapper);
        //查询 退换详情
        for (SelGoodsLogistics selGoodsLogistics : list) {
            List<SelGoodsLogisticsDetail> details = this.selGoodsLogisticsDetailService.getListBy(selGoodsLogistics.getId());
            selGoodsLogistics.setSelGoodsLogisticsDetails(details);
        }
        byId.setGetSelGoodsLogisticsDetails(list);
        //查询发货信息
        QueryWrapper<SelGoodsLogistics> selWrapper = new QueryWrapper<>();
        selWrapper.eq("record_id", byId.getId());
        selWrapper.eq("module_type", PurEnum.moduleTypeBylogistics.XSHH.getCode());
        selWrapper.eq("good_type", PurEnum.goodSellType.HH.getCode());
        selWrapper.eq("is_deleted", false);
        List<SelGoodsLogistics> selList = this.selGoodsLogisticsService.list(selWrapper);
        for (SelGoodsLogistics selGoodsLogistics : selList) {
            List<SelGoodsLogisticsDetail> details = this.selGoodsLogisticsDetailService.getListBy(selGoodsLogistics.getId());
            selGoodsLogistics.setSelGoodsLogisticsDetails(details);
        }
        byId.setSendSelGoodsLogisticsDetails(selList);
        return byId;
    }

    /**
     * 删除
     *
     * @param recordId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBy(String recordId) {
        boolean b = this.removeById(recordId);
        if (b) {
            QueryWrapper<SelBarterGoodsRecordsDetail> qw = new QueryWrapper<>();
            qw.eq("record_id", recordId);
            qw.eq("is_deleted", false);
            boolean remove = this.selBarterGoodsRecordsDetailService.remove(qw);
            if (remove) {
                return true;
            }
        }
        return false;
    }

    /**
     * 添加换货记录
     *
     * @param selBarterGoodRecordsUpdateForm
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int addLogisticsInfo(SelGoodsLogisticsDetailAddForm selBarterGoodRecordsUpdateForm) {
        //添加发货记录
        SelGoodsLogistics selGoodsLogistics = new SelGoodsLogistics();
        BeanUtil.copyProperties(selBarterGoodRecordsUpdateForm, selGoodsLogistics, false);
        selGoodsLogistics.setCreateTime(LocalDateTime.now());
        selGoodsLogistics.setModifier(JwtUtils.getLoginUserId());
        selGoodsLogistics.setCreator(JwtUtils.getLoginUserId());
        //code
        String code = UniqueIdGeneratorUtil.generateUniqueId("THWL", "yyyyMMdd", 1000, 9999);
        selGoodsLogistics.setCode(code);
        selGoodsLogistics.setCreatorName(JwtUtils.getLoginUsername());
        boolean save = selGoodsLogisticsService.save(selGoodsLogistics);
        if (save) {
            //拿到详情
            List<SelGoodsLogisticsDetail> formDetails = selBarterGoodRecordsUpdateForm.getDetails();
            for (SelGoodsLogisticsDetail formDetail : formDetails) {
                formDetail.setLogisticsId(selGoodsLogistics.getId());
                formDetail.setCreateTime(LocalDateTime.now());
                formDetail.setModifier(JwtUtils.getLoginUserId());
                formDetail.setCreatorName(JwtUtils.getLoginUsername());
                formDetail.setCreator(JwtUtils.getLoginUserId());
            }
            //插入发货详情
            boolean saved = selGoodsLogisticsDetailService.saveBatch(formDetails);

            if (saved) {
                //1. 修改record的信息
                Long recordId = selBarterGoodRecordsUpdateForm.getRecordId();
                SelBarterGoodsRecords byId = this.getById(recordId);
                //收货
                if (selBarterGoodRecordsUpdateForm.getGoodType().equals(PurEnum.goodSellType.TH.getCode())) {
                    //查询当前是否全部签收完毕
                    QueryWrapper<SelBarterGoodsRecordsDetail> detailQueryWrapper = new QueryWrapper<>();
                    detailQueryWrapper.eq("record_id", recordId);
                    List<SelBarterGoodsRecordsDetail> list = this.selBarterGoodsRecordsDetailService.list(detailQueryWrapper);
                    AtomicReference<Boolean> isOk = new AtomicReference<>(true);
                    if (CollectionUtils.isNotEmpty(list)) {
                        list.forEach(info -> {
                            //获取
                            BigDecimal result = this.baseMapper.getGetQuantityForLogistics(info.getId(), PurEnum.moduleTypeBylogistics.XSHH.getCode());
                            if (result == null || result.compareTo(info.getMainQuantity()) < 0) {
                                isOk.set(false);
                            }
                        });
                    }
                    if (isOk.get()) {
                        byId.setStatus(PurEnum.barterGoodStatus.YQS.getCode());
                    }
                }
                //设置状态为已收货
                byId.setUpdateTime(LocalDateTime.now());
                byId.setModifier(JwtUtils.getLoginUserId());
                byId.setModifierName(JwtUtils.getLoginUsername());
                byId.setFileName(selBarterGoodRecordsUpdateForm.getFileName());
                byId.setFileUrl(selBarterGoodRecordsUpdateForm.getFileUrl());
                byId.setMethod(selBarterGoodRecordsUpdateForm.getReturnType());
                boolean b = this.updateById(byId);
                if (b) {
                    return 1;
                }
            }
        }
        return 0;
    }
}
